package sky.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import sky.domain.Airport;
import sky.domain.Flight;
import sky.domain.Ticket;
import sky.domain.User;
import sky.service.*;
import sky.tro.Blah;
import sky.tro.FlightLayer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 24.04.13
 * Time: 18:00
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class MainController {

    @Autowired
    private FlightService flightService;
    @Autowired
    private PlaneService planeService;
    @Autowired
    private AirportService airportService;
    @Autowired
    private CountryService countryService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String listAll() {
        return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "../../login";
    }

    protected Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    User getCurrentUser() {
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name;
        if (object instanceof UserDetails) {
            name = ((UserDetails) object).getUsername();
        }
        else {
            name = object.toString();
        }
        return userService.getUserByName(name);
    }

    @ModelAttribute("uzver")
    public User getUzver() {
        User user =  getCurrentUser();
        return user;
    }

    @ModelAttribute("showAuth")
    public Integer getAuth() {
        for (GrantedAuthority authority: getAuthentication().getAuthorities()) {
            if (authority.getAuthority().equals("ROLE_USER")) {
                return 1;
            }
            if (authority.getAuthority().equals("ROLE_ADMIN")) {
                return 2;
            }
        }
        return 0;
    }

    @RequestMapping("/")
    public String home(@CookieValue(required = false, value = "currentAirport") String currentAirport) {
        if (currentAirport == null) return "redirect:/shedule";
        return "redirect:/index";
    }

    @RequestMapping(value = "/registration", method = RequestMethod.GET)
    public String registration(Map<String , Object> map) {
        map.put("user", new User());
        return "registration";
    }

    @RequestMapping(value = "/registration", method = RequestMethod.POST)
    public String mainRegistration(@ModelAttribute("user") User user,
                                   BindingResult result) {
        userService.addUser(user);
        return "index";
    }

    @ModelAttribute("SFlightList")
    public ArrayList<FlightLayer> sidebarShedule(@CookieValue(required = false, value = "currentAirport") String currentAirport) {
        if (currentAirport == null) currentAirport = "Minsk";
        Airport airport = airportService.getAirportByName(currentAirport);
        Date now = new Date();
        SimpleDateFormat formatter1 = new SimpleDateFormat("dd.MM.yyyy");
        ArrayList<FlightLayer> flightList = new ArrayList<FlightLayer>();
        for(Flight flight: airport.getFlightsIn()) {
            if (formatter1.format(now).equals(formatter1.format(flight.getDestinationDate()))) flightList.add(new FlightLayer(flight.getDestinationDate(),
                    "Arrive", flight.getDepartureAirport().getName()));
        }
        for(Flight flight: airport.getFlightsOut()) {
            if (formatter1.format(now).equals(formatter1.format(flight.getDepartureDate()))) flightList.add(new FlightLayer(flight.getDepartureDate(),
                    "Depart", flight.getDestinationAirport().getName()));
        }
        Collections.sort(flightList, new Comparator<FlightLayer>() {
            public int compare(FlightLayer o1, FlightLayer o2) {
                return o1.getDate().compareTo(o2.getDate());
            }
        });
        return flightList;
    }

    @ModelAttribute("currentAirport")
    public String currentAirport(@CookieValue(required = false, value = "currentAirport") String currentAirport) {
        if (currentAirport == null) currentAirport = "Minsk";
        return currentAirport;
    }


    @ModelAttribute("userFlightList")
    public ArrayList<Flight> shedule() {
        User user = getCurrentUser();
        ArrayList <Flight> flightList = new ArrayList<Flight>();
        if (user != null) {
            Date now = new Date();
            SimpleDateFormat formatter1 = new SimpleDateFormat("dd.MM.yyyy");
            for (Ticket ticket: user.getTickets()) {
                flightList.add(ticket.getFlight());
            }
            Collections.sort(flightList, new Comparator<Flight>() {
                public int compare(Flight o1, Flight o2) {
                    return o1.getDepartureDate().compareTo(o2.getDepartureDate());
                }
            });
        }
        return flightList;
    }

    @RequestMapping(value = "/shedule", method = RequestMethod.GET)
    public String shedule(@CookieValue(required = false, value = "currentAirport") String currentAirport,
                          Map<String, Object> map) {
        if (currentAirport == null) currentAirport = "Minsk";
        map.put("currentAirport", currentAirport);
        ArrayList<String> allAirports = new ArrayList<String>();
        for(Airport airport1: airportService.listAirport()) {
            allAirports.add(airport1.getName());
        }
        map.put("allAirports", allAirports);
        map.put("string", new Blah());
        return "shedule";
    }

    @RequestMapping(value = "/shedule", method = RequestMethod.POST)
    public String shedule(@ModelAttribute("string") Blah blah,
                          HttpServletResponse response) {
        response.addCookie(new Cookie("currentAirport", blah.getValue()));
        return "redirect:/index";
    }

    @RequestMapping(value = "/file", method = RequestMethod.GET)
    public String file(@RequestParam("currentAirport") String currentAirport) {
        if (currentAirport == null) currentAirport = "Minsk";
        Airport airport = airportService.getAirportByName(currentAirport);
        Date now = new Date();
        SimpleDateFormat formatter1 = new SimpleDateFormat("dd.MM.yyyy");
        ArrayList<FlightLayer> flightList = new ArrayList<FlightLayer>();
        for(Flight flight: airport.getFlightsIn()) {
            if (formatter1.format(now).equals(formatter1.format(flight.getDestinationDate()))) flightList.add(new FlightLayer(flight.getDestinationDate(),
                    "Arrive", flight.getDepartureAirport().getName()));
        }
        for(Flight flight: airport.getFlightsOut()) {
            if (formatter1.format(now).equals(formatter1.format(flight.getDepartureDate()))) flightList.add(new FlightLayer(flight.getDepartureDate(),
                    "Depart", flight.getDestinationAirport().getName()));
        }
        Collections.sort(flightList, new Comparator<FlightLayer>() {
            public int compare(FlightLayer o1, FlightLayer o2) {
                return o1.getDate().compareTo(o2.getDate());
            }
        });
        String toFile = "";
        for (FlightLayer flightLayer: flightList) {
            toFile = toFile + flightLayer.getStatus() + " ";
            toFile = toFile + flightLayer.getAirportName() + " ";
            toFile = toFile + flightLayer.getDate();
            toFile = toFile + System.lineSeparator();
        }
        File file = new File("D:/test.txt");
        try {
            FileOutputStream outFile = new FileOutputStream(file);
            outFile.write(toFile.getBytes());
            outFile.close();
        } catch (FileNotFoundException ignored) {} catch (IOException ignored) {}
        return "index";
    }
}
